<?php
/**
 * Created by zengxianfen on 2020/7/17 11:32.
 */

namespace App\Model\Service;


use App\Exception\ServiceException;
use App\Model\Repository\CompanyRepository;
use App\Model\Repository\UserRepository;
use Hyperf\Config\Annotation\Value;
use Hyperf\Di\Annotation\Inject;

class CompanyService extends BaseService
{
    const ACTIVED = 'ACTIVED';
    const CANCEL = 'CANCEL';

    const SUPERADMIN = 'SUPERADMIN';
    /**
     * @Inject()
     * @var CompanyRepository
     */
    protected $repository;


    /**
     * @Inject()
     * @var UserRepository
     */
    protected $userRepository;

    /**
     * @Value("password_salt")
     * @var string
     */
    protected $password_salt;


    /**
     * @author zengxianfen 2020/7/20
     * @param $name
     * @param $id
     * @return bool
     * @throws ServiceException
     */
    public function checkCompanyExisted($name, $id = '') {
        $model = $this->repository->getModel();
        $exists = $model::query()->where('name', $name)->first();
        if (!empty($exists) && $exists->id != $id) {
            throw new ServiceException("公司名称已被使用，请确认");
        }
        return true;
    }

    /**
     * 插入公司和公司管理员用户
     * @author zengxianfen 2020/7/20
     * @param array $params
     * @return bool
     */
    public function createCompanyAndUser(array $params) {
        $this->repository->create([
            'name' => $params['name'],
            'phone' => $params['phone'],
            'status' => self::ACTIVED,
        ]);
        $this->userRepository->create([
            'name' => $params['nick_name'],
            'phone' => $params['phone'],
            'password' => md5($params['password'].$this->password_salt),
            'type' => self::SUPERADMIN,
        ]);
        return true;
    }
}